package com.hj.dapp.config.security;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.hj.dapp.common.resp.RestResp;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

import static com.hj.dapp.config.exp.BusinessErrorEnum.UN_AUTHORIZED;

/**
 * @author 胡奥程
 * @version 1.0
 * @date 2023/12/29
 */
public class UserAuthAccessDeniedHandler implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        out.write(new ObjectMapper().writeValueAsString(RestResp.error(UN_AUTHORIZED)));
        out.flush();
        out.close();

    }
}
